import 'package:flutter/material.dart';
import 'dart:math' as math;

/// 手绘风格的图标组件
class HandDrawnIcon extends StatelessWidget {
  final IconData icon;
  final double size;
  final Color color;
  final double wobble;
  final double thickness;
  
  const HandDrawnIcon({
    Key? key,
    required this.icon,
    this.size = 24.0,
    this.color = Colors.black,
    this.wobble = 2.0,
    this.thickness = 2.0,
  }) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      size: Size(size, size),
      painter: _HandDrawnIconPainter(
        icon: icon,
        color: color,
        wobble: wobble,
        thickness: thickness,
      ),
    );
  }
}

/// 手绘表情图标
class HandDrawnEmotionIcon extends StatelessWidget {
  final int moodType;
  final double size;
  final Color? color;
  
  const HandDrawnEmotionIcon({
    Key? key,
    required this.moodType,
    this.size = 40.0,
    this.color,
  }) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      size: Size(size, size),
      painter: _HandDrawnEmotionPainter(
        moodType: moodType,
        color: color ?? _getMoodColor(moodType, context),
      ),
    );
  }
  
  Color _getMoodColor(int moodType, BuildContext context) {
    final theme = Theme.of(context);
    switch (moodType) {
      case 1: // 非常糟糕
        return Colors.red.shade700;
      case 2: // 糟糕
        return Colors.orange.shade700;
      case 3: // 中性
        return Colors.yellow.shade700;
      case 4: // 良好
        return Colors.lightGreen.shade600;
      case 5: // 非常好
        return Colors.green.shade600;
      default:
        return theme.primaryColor;
    }
  }
}

/// 手绘图标绘制器
class _HandDrawnIconPainter extends CustomPainter {
  final IconData icon;
  final Color color;
  final double wobble;
  final double thickness;
  
  _HandDrawnIconPainter({
    required this.icon,
    required this.color,
    required this.wobble,
    required this.thickness,
  });
  
  @override
  void paint(Canvas canvas, Size size) {
    final textPainter = TextPainter(
      text: TextSpan(
        text: String.fromCharCode(icon.codePoint),
        style: TextStyle(
          fontSize: size.width * 0.8,
          fontFamily: icon.fontFamily,
          color: Colors.transparent,
        ),
      ),
      textDirection: TextDirection.ltr,
    );
    
    textPainter.layout();
    textPainter.paint(
      canvas,
      Offset(
        (size.width - textPainter.width) / 2,
        (size.height - textPainter.height) / 2,
      ),
    );
    
    final iconPath = _extractPathFromTextPainter(textPainter, size);
    final handDrawnPath = _createHandDrawnPath(iconPath);
    
    final paint = Paint()
      ..color = color
      ..style = PaintingStyle.stroke
      ..strokeWidth = thickness
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..isAntiAlias = true;
    
    canvas.drawPath(handDrawnPath, paint);
  }
  
  Path _extractPathFromTextPainter(TextPainter textPainter, Size size) {
    // 这是一个简化的实现，实际上我们无法直接从TextPainter提取路径
    // 所以我们基于图标类型创建一些基本形状
    final path = Path();
    final center = Offset(size.width / 2, size.height / 2);
    final radius = size.width * 0.4;
    
    // 创建一个简单的圆形路径作为基础
    path.addOval(Rect.fromCircle(center: center, radius: radius));
    
    // 根据图标类型添加一些特征
    if (icon.codePoint % 3 == 0) {
      // 添加一些线条
      path.moveTo(center.dx - radius, center.dy);
      path.lineTo(center.dx + radius, center.dy);
      path.moveTo(center.dx, center.dy - radius);
      path.lineTo(center.dx, center.dy + radius);
    } else if (icon.codePoint % 3 == 1) {
      // 添加一个矩形
      path.addRect(Rect.fromCenter(
        center: center,
        width: radius * 1.5,
        height: radius * 1.5,
      ));
    }
    
    return path;
  }
  
  Path _createHandDrawnPath(Path sourcePath) {
    final handDrawnPath = Path();
    final random = _PseudoRandom(icon.codePoint);
    
    // 遍历原始路径并添加随机偏移
    for (var i = 0; i < 100; i++) {
      final t = i / 100;
      final metric = sourcePath.computeMetrics().first;
      if (t > metric.length) break;
      
      final pos = metric.getTangentForOffset(t * metric.length)?.position;
      if (pos == null) continue;
      
      final offset = Offset(
        random.nextDouble() * wobble * 2 - wobble,
        random.nextDouble() * wobble * 2 - wobble,
      );
      
      final newPos = pos + offset;
      
      if (i == 0) {
        handDrawnPath.moveTo(newPos.dx, newPos.dy);
      } else {
        handDrawnPath.lineTo(newPos.dx, newPos.dy);
      }
    }
    
    return handDrawnPath;
  }
  
  @override
  bool shouldRepaint(_HandDrawnIconPainter oldDelegate) {
    return oldDelegate.icon != icon ||
        oldDelegate.color != color ||
        oldDelegate.wobble != wobble ||
        oldDelegate.thickness != thickness;
  }
}

/// 手绘表情绘制器
class _HandDrawnEmotionPainter extends CustomPainter {
  final int moodType;
  final Color color;
  
  _HandDrawnEmotionPainter({
    required this.moodType,
    required this.color,
  });
  
  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = size.width * 0.4;
    final random = _PseudoRandom(moodType * 1000);
    
    // 绘制手绘风格的圆脸
    final facePath = _createWobblyCircle(center, radius, random);
    
    final paint = Paint()
      ..color = color
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..isAntiAlias = true;
    
    canvas.drawPath(facePath, paint);
    
    // 绘制眼睛
    final eyeRadius = radius * 0.15;
    final eyeOffsetX = radius * 0.5;
    final eyeOffsetY = radius * 0.2;
    
    final leftEyeCenter = Offset(
      center.dx - eyeOffsetX + random.nextDouble() * 2 - 1,
      center.dy - eyeOffsetY + random.nextDouble() * 2 - 1,
    );
    
    final rightEyeCenter = Offset(
      center.dx + eyeOffsetX + random.nextDouble() * 2 - 1,
      center.dy - eyeOffsetY + random.nextDouble() * 2 - 1,
    );
    
    final leftEyePath = _createWobblyCircle(leftEyeCenter, eyeRadius, random);
    final rightEyePath = _createWobblyCircle(rightEyeCenter, eyeRadius, random);
    
    canvas.drawPath(leftEyePath, paint);
    canvas.drawPath(rightEyePath, paint);
    
    // 根据情绪类型绘制不同的嘴巴
    final mouthPath = Path();
    final mouthWidth = radius * 1.2;
    final mouthHeight = radius * 0.6;
    final mouthY = center.dy + radius * 0.3;
    
    switch (moodType) {
      case 1: // 非常糟糕
        _drawSadMouth(canvas, center, radius, paint, random, -0.8);
        break;
      case 2: // 糟糕
        _drawSadMouth(canvas, center, radius, paint, random, -0.4);
        break;
      case 3: // 中性
        _drawNeutralMouth(canvas, center, radius, paint, random);
        break;
      case 4: // 良好
        _drawHappyMouth(canvas, center, radius, paint, random, 0.4);
        break;
      case 5: // 非常好
        _drawHappyMouth(canvas, center, radius, paint, random, 0.8);
        break;
      default:
        _drawNeutralMouth(canvas, center, radius, paint, random);
    }
  }
  
  // 创建波浪圆
  Path _createWobblyCircle(Offset center, double radius, _PseudoRandom random) {
    final path = Path();
    final segments = 20;
    
    for (var i = 0; i <= segments; i++) {
      final theta = i * 2 * math.pi / segments;
      final wobble = 1.0 + (random.nextDouble() * 0.1 - 0.05);
      final x = center.dx + radius * wobble * math.cos(theta);
      final y = center.dy + radius * wobble * math.sin(theta);
      
      if (i == 0) {
        path.moveTo(x, y);
      } else {
        path.lineTo(x, y);
      }
    }
    
    path.close();
    return path;
  }
  
  // 绘制悲伤的嘴巴
  void _drawSadMouth(Canvas canvas, Offset center, double radius, 
                     Paint paint, _PseudoRandom random, double intensity) {
    final mouthPath = Path();
    final mouthWidth = radius * 0.8;
    final mouthHeight = radius * 0.4 * intensity.abs();
    final mouthY = center.dy + radius * 0.3;
    
    mouthPath.moveTo(
      center.dx - mouthWidth / 2 + random.nextDouble() * 2 - 1,
      mouthY + random.nextDouble() * 2 - 1,
    );
    
    mouthPath.quadraticBezierTo(
      center.dx + random.nextDouble() * 4 - 2,
      mouthY + mouthHeight + random.nextDouble() * 4 - 2,
      center.dx + mouthWidth / 2 + random.nextDouble() * 2 - 1,
      mouthY + random.nextDouble() * 2 - 1,
    );
    
    canvas.drawPath(mouthPath, paint);
  }
  
  // 绘制中性的嘴巴
  void _drawNeutralMouth(Canvas canvas, Offset center, double radius, 
                         Paint paint, _PseudoRandom random) {
    final mouthPath = Path();
    final mouthWidth = radius * 0.8;
    final mouthY = center.dy + radius * 0.3;
    
    final startX = center.dx - mouthWidth / 2 + random.nextDouble() * 2 - 1;
    final endX = center.dx + mouthWidth / 2 + random.nextDouble() * 2 - 1;
    final startY = mouthY + random.nextDouble() * 2 - 1;
    final endY = mouthY + random.nextDouble() * 2 - 1;
    
    mouthPath.moveTo(startX, startY);
    
    // 添加一些小的波动使线条看起来像手绘的
    final segments = 5;
    for (var i = 1; i <= segments; i++) {
      final t = i / segments;
      final x = startX + (endX - startX) * t;
      final y = startY + (endY - startY) * t + random.nextDouble() * 2 - 1;
      mouthPath.lineTo(x, y);
    }
    
    canvas.drawPath(mouthPath, paint);
  }
  
  // 绘制开心的嘴巴
  void _drawHappyMouth(Canvas canvas, Offset center, double radius, 
                       Paint paint, _PseudoRandom random, double intensity) {
    final mouthPath = Path();
    final mouthWidth = radius * 0.8;
    final mouthHeight = radius * 0.4 * intensity.abs();
    final mouthY = center.dy + radius * 0.3;
    
    mouthPath.moveTo(
      center.dx - mouthWidth / 2 + random.nextDouble() * 2 - 1,
      mouthY + random.nextDouble() * 2 - 1,
    );
    
    mouthPath.quadraticBezierTo(
      center.dx + random.nextDouble() * 4 - 2,
      mouthY - mouthHeight + random.nextDouble() * 4 - 2,
      center.dx + mouthWidth / 2 + random.nextDouble() * 2 - 1,
      mouthY + random.nextDouble() * 2 - 1,
    );
    
    canvas.drawPath(mouthPath, paint);
  }
  
  @override
  bool shouldRepaint(_HandDrawnEmotionPainter oldDelegate) {
    return oldDelegate.moodType != moodType ||
        oldDelegate.color != color;
  }
}

/// 伪随机数生成器，用于生成一致的"随机"效果
class _PseudoRandom {
  int _seed;
  
  _PseudoRandom(this._seed);
  
  double nextDouble() {
    _seed = (_seed * 1103515245 + 12345) & 0x7FFFFFFF;
    return _seed / 0x7FFFFFFF;
  }
} 